package dl.transactionscript.service;

import java.sql.ResultSet;
import java.sql.SQLException;

import dl.common.service.iface.RecognitionServiceInterface;
import dl.exception.handler.ApplicationException;
import dl.martinfowler.wrapper.MfDate;
import dl.martinfowler.wrapper.Money;
import dl.transactionscript.gateway.TableDataGateway;

public class RecognitionService implements RecognitionServiceInterface{

	private TableDataGateway tableDataGateway;

	public RecognitionService() {
		tableDataGateway = new TableDataGateway();
	}

	public Money recognizedRevenue(long contractNumber, MfDate asOf)
			throws ApplicationException {
		Money result = Money.dollars(0);
		try {
			ResultSet rs = tableDataGateway.findRecognitionsFor(contractNumber,
					asOf);
			while (rs.next()) {
				result = result.add(Money.dollars(rs.getBigDecimal("amount")
						.doubleValue()));
			}
		} catch (SQLException e) {
			throw new ApplicationException(e);
		}
		return result;
	}

	public void calculateRevenueRecognitions(long contractNumber)
			throws ApplicationException {
		try {
			ResultSet contracts = tableDataGateway.findContract(contractNumber);
			contracts.next();
			Money totalRevenue = Money.dollars(contracts.getBigDecimal(
					"revenue").doubleValue());
			MfDate recognitionDate = new MfDate(contracts.getDate("dateSigned"));
			String type = contracts.getString("type");
			if (type.equals("S")) {
				Money[] allocation = totalRevenue.allocate(3);
				tableDataGateway.insertRecognition(contractNumber,
						allocation[0], recognitionDate);
				tableDataGateway.insertRecognition(contractNumber,
						allocation[1], recognitionDate.addDays(60));
				tableDataGateway.insertRecognition(contractNumber,
						allocation[2], recognitionDate.addDays(90));
			} else if (type.equals("W")) {
				tableDataGateway.insertRecognition(contractNumber,
						totalRevenue, recognitionDate);
			} else if (type.equals("D")) {
				Money[] allocation = totalRevenue.allocate(3);
				tableDataGateway.insertRecognition(contractNumber,
						allocation[0], recognitionDate);
				tableDataGateway.insertRecognition(contractNumber,
						allocation[1], recognitionDate.addDays(30));
				tableDataGateway.insertRecognition(contractNumber,
						allocation[2], recognitionDate.addDays(60));
			}
		} catch (SQLException e) {
			throw new ApplicationException(e);
		}
	}
	
	public void showRecognizedRevenue() throws ApplicationException{
		try {
			ResultSet rs = tableDataGateway.findRevenueRecognitions();
			System.out.println("Revenue Recogntions : ");
			while (rs.next()) {
				System.out.println(rs.getInt(1) + ":" + rs.getString(2) + ":"
						+ rs.getString(3));
			}
		} catch (SQLException e) {
			throw new ApplicationException(e);
		}
	}

}
